import React, { Component } from 'react';
import { NavBar, Form, Input, Button, Toast } from 'antd-mobile'
import service from '../../api';
import '../../style/Register/Code.scss'


// interface State {
//     tel: string
//     code: any
//     time: any
//     timed: any
// }
class Code extends Component<any, any>{
    constructor(props: any) {
        super(props);
        this.state = {
            tel: '',
            code: '',
            time: 6,
            timed: null
        }
    }

    // 获取短信验证码 
    async obCode(value: any) {
        var res = await service.user.dosendmsgcode({ tel: value.name, telcode: '' })
        console.log(res);
        if (res.data.code == 200) {
            var times = setTimeout(() => {
                Toast.show({
                    content: '发送成功',

                })
                this.setState({ code: res.data.data })
                clearTimeout(times)
            }, 3000)
        }
        clearInterval(this.state.timed)
        var timed = setInterval(() => {

            this.setState({
                time: this.state.time - 1
            })
            if (this.state.time == 0) {
                clearInterval(timed)
                this.setState({ time: 6 })
            }
        }, 1000)

    }
    // 验证短信验证法
    async onFinsh(value: any) {
        console.log(value);
        var res = await service.user.docheckcode({ tel: value.name, telcode: this.state.code })
        console.log(res);
        if (res.data.code == 200) {
            this.props.history.push('/password')
        } else {
            Toast.show({
                icon: 'fail',
                content: '验证码有误,请重新发送',
            })
        }
    }

    render() {
        return (
            <div className='code'>
                <div className="top">
                    <NavBar onBack={() => { this.props.history.go(-1) }}>注册</NavBar>
                </div>

                <Form
                    onFinish={(value) => { this.onFinsh(value) }}
                    footer={
                        <Button block type='submit' color='danger' size='large' shape='rounded'>
                            下一步
                        </Button>
                    }
                >
                    <Form.Item
                        extra={
                            <div className='extraPart'>
                                {
                                    this.state.time == 6 ?
                                        <a onClick={(value) => { this.obCode(value) }}>发送验证码</a> :
                                        <span className='time'>{this.state.time}</span>
                                }


                            </div>
                        }
                    >
                        <Input placeholder='请输入验证码' clearable value={this.state.code} />
                    </Form.Item>
                </Form>

            </div>
        );
    }
}

export default Code;